﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interactivity;
using UCL.Powersource;

namespace PowersourceUIToolkit
{
    /// <summary>
    /// Binds a View to a View model.
    /// </summary>
    public static class ViewModelBinder
    {
        /// <summary>
        /// Gets or sets a value indicating whether to apply conventions by default.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if conventions should be applied by default; otherwise, <c>false</c>.
        /// </value>
        public static bool ApplyConventionsByDefault = true;
        static readonly ILog Log = LogManager.GetLog(typeof(ViewModelBinder));

        /// <summary>
        /// Indicates whether or not the conventions have already been applied to the View.
        /// </summary>
        public static readonly DependencyProperty ConventionsAppliedProperty =
            DependencyProperty.RegisterAttached(
                "ConventionsApplied",
                typeof(bool),
                typeof(ViewModelBinder),
                null
                );

        /// <summary>
        /// Determines whether a View should have conventions applied to itForFE.
        /// </summary>
        /// <param name="View">The View to check.</param>
        /// <returns>Whether or not conventions should be applied to the View.</returns>
        public static bool ShouldApplyConventions(FrameworkElement view)
        {
            var overriden = View.GetApplyConventions(view);
            return overriden.GetValueOrDefault(ApplyConventionsByDefault);
        }

        /// <summary>
        /// Creates data bindings on the View's controls based on the provided properties.
        /// </summary>
        /// <remarks>Parameters include named Elements to search through and the type of View model to determine conventions for. Returns unmatched elements.</remarks>
        public static Func<IEnumerable<FrameworkElement>, Type, IEnumerable<FrameworkElement>> BindProperties = (namedElements, viewModelType) =>
        {
            var unmatchedElements = new List<FrameworkElement>();

            foreach (var element in namedElements)
            {
                var cleanName = element.Name.Trim('_');
                var parts = cleanName.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);

                var property = viewModelType.GetPropertyCaseInsensitive(parts[0]);
                var interpretedViewModelType = viewModelType;

                for (int i = 1; i < parts.Length && property != null; i++)
                {
                    interpretedViewModelType = property.PropertyType;
                    property = interpretedViewModelType.GetPropertyCaseInsensitive(parts[i]);
                }

                if (property == null)
                {
                    unmatchedElements.Add(element);
                    Log.Info("Binding Convention Not Applied: Element {0} did not match a property.", element.Name);
                    continue;
                }

                var convention = ConventionManager.GetElementConvention(element.GetType());
                if (convention == null)
                {
                    unmatchedElements.Add(element);
                    Log.Warn("Binding Convention Not Applied: No conventions configured for {0}.", element.GetType());
                    continue;
                }

                var applied = convention.ApplyBinding(
                    interpretedViewModelType,
                    cleanName.Replace('_', '.'),
                    property,
                    element,
                    convention
                    );

                if (applied)
                {
                    Log.Info("Binding Convention Applied: Element {0}.", element.Name);
                }
                else
                {
                    Log.Info("Binding Convention Not Applied: Element {0} has existing binding.", element.Name);
                    unmatchedElements.Add(element);
                }
            }

            return unmatchedElements;
        };

        /// <summary>
        /// Attaches instances of <see cref="ActionMessage"/> to the View's controls based on the provided methods.
        /// </summary>
        /// <remarks>Parameters include the named elements to search through and the type of View model to determine conventions for. Returns unmatched elements.</remarks>
        public static Func<IEnumerable<FrameworkElement>, Type, IEnumerable<FrameworkElement>> BindActions = (namedElements, viewModelType) =>
        {
            var methods = viewModelType.GetMethods();
            var unmatchedElements = namedElements.ToList();

            foreach (var method in methods)
            {
                var foundControl = unmatchedElements.FindName(method.Name);
                if (foundControl == null)
                {
                    Log.Info("Action Convention Not Applied: No actionable element for {0}.", method.Name);
                    continue;
                }

                unmatchedElements.Remove(foundControl);

                var triggers = Interaction.GetTriggers(foundControl);
                if (triggers != null && triggers.Count > 0)
                {
                    Log.Info("Action Convention Not Applied: Interaction.Triggers already set on {0}.", foundControl.Name);
                    continue;
                }

                var message = method.Name;
                var parameters = method.GetParameters();

                if (parameters.Length > 0)
                {
                    message += "(";

                    foreach (var parameter in parameters)
                    {
                        var paramName = parameter.Name;
                        var specialValue = "$" + paramName.ToLower();

                        if (MessageBinder.SpecialValues.ContainsKey(specialValue))
                            paramName = specialValue;

                        message += paramName + ",";
                    }

                    message = message.Remove(message.Length - 1, 1);
                    message += ")";
                }

                Log.Info("Action Convention Applied: Action {0} on element {1}.", method.Name, message);
                Message.SetAttach(foundControl, message);
            }

            return unmatchedElements;
        };

        /// <summary>
        /// Allows the developer to add custom handling of named elements which were not matched by any default conventions.
        /// </summary>
        public static Action<IEnumerable<FrameworkElement>, Type> HandleUnmatchedElements = (elements, viewModelType) => { };

        /// <summary>
        /// Binds the specified viewModel to the View.
        /// </summary>
        ///<remarks>Passes the the View model, View and creation Context (or null for default) to use in applying binding.</remarks>
        public static Action<IViewModel, DependencyObject, object> Bind = (viewModel, view, context) =>
        {
            Log.Trace("Binding {0} and {1}.", view, viewModel);

            if ((bool)view.GetValue(PowersourceUIToolkit.Bind.NoContextProperty))
            {
                Action.SetTargetWithoutContext(view, viewModel);
            }
            else
            {
                Action.SetTarget(view, viewModel);
            }

            //var viewAware = viewModel as IViewAware;
            //if (viewAware != null)
            //{
            //    Log.Info("Attaching {0} to {1}.", View, viewAware);
            //    viewAware.AttachView(View, Context);
            //}

            //if ((bool)View.GetValue(ConventionsAppliedProperty))
            //{
            //    return;
            //}

            //var element = View.GetFirstNonGeneratedView(View) as FrameworkElement;
           
            var element = view as FrameworkElement;
            if (element == null)
            {
                return;
            }

            if (!ShouldApplyConventions(element))
            {
                Log.Info("Skipping conventions for {0} and {1}.", element, viewModel);
                return;
            }

            var viewModelType = viewModel.GetType();
            var namedElements = BindingScope.GetNamedElements(element);

            namedElements = BindActions(namedElements, viewModelType);
            namedElements = BindProperties(namedElements, viewModelType);
            HandleUnmatchedElements(namedElements, viewModelType);
            view.SetValue(ConventionsAppliedProperty, true);
        };
    }

}
    

